﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CRMSimple.LogService.Configuration.FileConfiguration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CRMSimple.LogService.Configuration.FileConfigurationExtension.Json
{
    public class JsonConfigurationRoot : FileConfigurationRoot
    {
        public static readonly string KeyDelimiter = ":";

        //private Stream _readStream;
        //private Stream _wirteStream;
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected override Stream CreateReadStream()
        {
            //if (_readStream==null)
            //    _readStream=new FileStream(this.CheckDirectory(this.GetPhysicalFilePath(this.Path)), FileMode.OpenOrCreate,FileAccess.Read);
            //return _readStream;
            return new FileStream(this.CheckDirectory(this.GetPhysicalFilePath(this.Path)), FileMode.OpenOrCreate, FileAccess.Read);
        }
        protected override void Load(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                Json = JsonConvert.DeserializeObject(data) as JObject;
                foreach (var item in Json)
                {
                    this[item.Key] = item.Value.ToString();
                }
            }
        }
        public JObject Json
        {
            get;
            private set;
        }
        /// <summary>
        /// 写入配置文件流
        /// </summary>
        protected override byte[] GetWriteBytes()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (var item in this.Properties)
            {
                sb.Append("\"" + item.Key + "\"" + KeyDelimiter + GetValue( item.Value ));
            }
            var temp=sb.ToString();
            return Encoding.UTF8.GetBytes(temp.Substring(0, temp.Length - 1) + "}");
        }
        private string GetValue(string value)
        {
            if (value.IndexOf("{") > -1 || value.IndexOf("[") > -1)
                return value+",";
            else
                return "\"" + value + "\",";
        }
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected override Stream CreateWirteStream()
        {
            //if (_wirteStream == null)
            //    _wirteStream = new FileStream(this.CheckDirectory(this.GetPhysicalFilePath(this.Path)), FileMode.Create);
            //return _wirteStream;
            return new FileStream(this.CheckDirectory(this.GetPhysicalFilePath(this.Path)), FileMode.Create);
        }
    }
}
